package servlet;

import java.io.IOException;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.PageContext;

import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

/**
 * 文件上传下载 servlet
 *
 * @author bing.zhang06@hand-china.com 2021/7/24 21:22
 **/
@WebServlet(urlPatterns = {"/upload", "/download"})
public class UpDownLoadServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestURI = req.getRequestURI();
        if ("/upload".equals(requestURI)) {
            upload(req, resp);
        } else if ("/download".equals(requestURI)) {
            download(req, resp);
        }
    }

    private void download(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("filename");
        String url = "/uploadfiles/" + name;
        // 将响应的内容设置为通用的二进制流
        resp.setContentType("application/octet-stream");
        // attachment 告诉浏览器以附件的方式下载文件(弹出下载框)
        name = URLEncoder.encode(name, "utf-8");
        resp.addHeader("Content-Disposition", "attachment;filename=" + name);

        req.getRequestDispatcher(url).forward(req, resp);
        // 清空缓冲区:将服务端缓冲区的文件内容,立即权并不传送给客户端
        resp.flushBuffer();
    }

    public void upload(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            // 上传文件
            SmartUpload su = new SmartUpload();
            // 获得pageContext对象
            JspFactory factory = JspFactory.getDefaultFactory();
            PageContext pageContext = factory.getPageContext(this, req, resp, null, false, 1024, true);
            su.initialize(pageContext);
            su.setCharset("utf-8");
            // 实现文件的上传
            su.upload();

            File file = su.getFiles().getFile(0);
            //得到文件的基本信息
            String filename = file.getFileName();
            String type = file.getContentType();
            System.out.println("type=" + type);
            String url = "/uploadfiles/" + filename;
            System.out.println(url);

            //将上传文件保存到指定目录
            file.saveAs(url, SmartUpload.SAVE_VIRTUAL);
            req.setAttribute("filename", filename);

            String uname = su.getRequest().getParameter("uname");
            System.out.println("uname=" + uname);

            // 上传成功,转发至成功页面
            req.getRequestDispatcher("success.jsp").forward(req, resp);
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }
    }
}
